<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Content;
use App\Models\ContentItem;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class ContentController extends Controller
{
    public function lists(Request $request): JsonResponse
    {
        return $this->success(Content::query()->with(['items'])->orderByDesc('id')->paginate($request->input('limit', 10)));
    }

    public function updateOrCreate(Request $request): JsonResponse
    {
        try {
            $this->validate($request, [
                'title' => 'required',
            ], [
                'title.required' => '请输入标题'
            ]);
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        }
        $res = Content::query()->updateOrCreate(
            ['id' => $request->input('id')],
            [
                'key' => $request->input('key'),
                'title' => $request->input('title'),
            ]
        );
        return $res ? $this->success($res) : $this->error('操作失败');
    }

    // 子集
    public function updateOrCreateItem(Request $request): JsonResponse
    {
        try {
            $this->validate($request, [
                'title' => 'required',
                'content_id' => 'required',
            ], [
                'title.required' => '请输入标题',
                'content_id.required' => '内容选择错误'
            ]);
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        }
        $res = ContentItem::query()->updateOrCreate(
            ['id' => $request->input('id')],
            [
                'title' => $request->input('title'),
                'content' => $request->input('content'),
                'images' => implode(',', $request->input('images')),
                'content_id' => $request->input('content_id'),
            ]
        );
        return $res ? $this->success($res) : $this->error('操作失败');
    }

    public function delete(Request $request): JsonResponse
    {
        $res = Content::query()->where('id', $request->input('id'))->delete();
        return $res ? $this->success() : $this->error('操作失败');
    }

    public function deleteItem(Request $request): JsonResponse
    {
        $res = ContentItem::query()->where('id', $request->input('id'))->delete();
        return $res ? $this->success() : $this->error('操作失败');
    }
}
